package com.ynny.service;

import com.ynny.bean.Book;
import com.ynny.bean.User;
import com.ynny.dao.BookDao;
import com.ynny.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BookServiceImpl implements BookService{

    @Autowired
    BookDao bookDao;


    @Autowired
    UserService userService;


    //事务注解

    @Transactional(isolation = Isolation.REPEATABLE_READ)
    @Override
    public int buyBook(Integer userId, Integer bookId) {
        //买书逻辑
        //事务的传播行为
        // 加入  Propagation.REQUIRED
        // 或者 新建
        //1.操作图书 获取图书价格
        int price = cheekBook(bookId);
        //2.操作用户
        int res = userService.checkUser(userId, price);

        return res;

    }


    @Transactional
    public int cheekBook(Integer bookId){

        //1.查询图书价格
        // 1.2 查询图书是否存在
        Book book = bookDao.selectBookById(bookId);
        if (book == null){

            //-1 图书不存在
            return -1;
        }
        //图书价格
        Integer price = book.getPrice();
        //2.修改图书库存
        if (book == null){
            //图书不存在
            return -2;
        }
        //2.2 判断库存是否足够
        Integer stock = book.getStock();
        if (stock < 1){
            //库存不足
            return -3;
        }
        int i = bookDao.updateBookStock(bookId);

        if (i != 1){
            // 服务器异常 库存修改失败
            return -4;
        }

        return price;
    }


}
